import balanceBaseUtils from "../../utils/astUtils/balanceBaseUtils/balanceBaseUtils";
import { PBalanceInfo, LoadKeyResponse } from "./types/loadKey";
import { ConfigAppParams, ConfigAppResponse } from "./types/configApp";
import { GetBalanceNoParams, GetBalanceNoResponse } from "./types/getBalanceNo";
import { GetTimeResponse } from "./types/getTime";

const baseApi = "http://dev.mark.satrace.cn";

const getBalanceNo = async (params: GetBalanceNoParams): Promise<GetBalanceNoResponse> => {
  const response = await fetch(`${baseApi}/api/v2/balance/get_balance_no`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(params),
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  const data = (await response.json()) as GetBalanceNoResponse;
  return data;
};

const getTime = async (): Promise<GetTimeResponse> => {
  const response = await fetch(`${baseApi}/api/v2/balance/get_time`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
  });
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  const data = (await response.json()) as GetTimeResponse;
  return data;
};

const loadKey = async (params: PBalanceInfo): Promise<LoadKeyResponse> => {
  params = paramsTransition(params);
  const response = await fetch(`${baseApi}/api/v2/balance/load_key`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(params),
  });
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  const data = (await response.json()) as LoadKeyResponse;
  return data;
};

const config_app = async (params: ConfigAppParams): Promise<ConfigAppResponse> => {
  const response = await fetch(`${baseApi}/common-device/config_app`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(params),
  });
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  const data = (await response.json()) as ConfigAppResponse;
  return data;
};

const orgApi = {
  getBalanceNo,
  getTime,
  loadKey,
  config_app,
};
export default orgApi;

//处理请求参数 --- 添加上固定的key和timestamp和sign
const paramsTransition = <T extends object>(params: T): T => {
  return {
    ...params,
    key: balanceBaseUtils.getKey(),
    timestamp: balanceBaseUtils.getTime(),
    sign: balanceBaseUtils.getTime(),
  };
};
